using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;

namespace Fodee.DataAccess
{
    public abstract class DABase
    {
        
        private Database _db;
        private DbConnection connection;

        /// <summary>
        /// Default constructor
        /// </summary>
        public DABase()
        {
            // Create the Database object, using the default database service.
            // The default database service is determined through configuration.
            _db = DatabaseFactory.CreateDatabase();
        }

        public DABase(string databaseName)
        {
            // Create the Database object, using the default database service.
            // The default database service is determined through configuration.
            _db = DatabaseFactory.CreateDatabase(databaseName);

        }

        /// <summary>
        /// Open and returns a connection
        /// </summary>
        /// <returns>Returns DbConnection containing the opened connection</returns>
        public DbConnection GetConnection()
        {
            connection = _db.CreateConnection();
            connection.Open();

            return connection;
        }

        /// <summary>
        /// Close and dispose of a connection
        /// </summary>
        /// <param name="connection">The DbConnection object to be close</param>
        public void CloseConnection(DbConnection connection)
        {
            if (connection != null)
            {
                connection.Close();
                connection.Dispose();
            }
        }

        public void CloseConnection()
        {
            if (connection != null)
            {
                connection.Close();
                connection.Dispose();
            }
        }

        /// <summary>
        /// Get the database object
        /// </summary>
        protected Database Db
        {
            get
            {
                return _db;
            }
        }
    }
}
